package com.dodo.videoEdit.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.dodo.proiectCore.util.LogUtil;

import java.util.HashMap;
import java.util.Map;

import static com.vector.update_app.utils.AppUpdateUtils.getDisplayMetrics;


/**
 * @author zhoubo
 * @date 2020/8/13
 * @describe
 */
public class DragViewGroup extends ViewGroup {

    //行数
    private int rowNum = 3;
    //列数
    private int columnNum = 4;
    //间距
    private int spacingValue = 10;
    //子view宽度
    private int childWidth;
    //子view高度
    private int childHeight;
    //数据载体
    private int[]  markArray ;

    private int mySpecValue;

    //背景画笔
    private Paint paint;
    //背景格子
    private RectF rectF;

    Map<Integer, View> cancelViews = new HashMap<>();
    private Rect rect;

    public int getChildWidth() {
        return childWidth;
    }

    public int getChildHeight() {
        return childHeight;
    }

    public DragViewGroup(Context context) {
        this(context,null);
    }

    public DragViewGroup(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public DragViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr,0);
    }

    public DragViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = (width/columnNum)*rowNum;
        mySpecValue = dp2px(getContext(),spacingValue);
        childWidth = (width-(columnNum-1)* mySpecValue)/columnNum;
        childHeight = (height-(rowNum-1)* mySpecValue)/rowNum;
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).measure(childWidth,childHeight);
        }
        setMeasuredDimension(width,height);
    }
    private void init(){
        /*
         * 画笔样式分三种：
         * 1.Paint.Style.STROKE：描边
         * 2.Paint.Style.FILL_AND_STROKE：描边并填充
         * 3.Paint.Style.FILL：填充
         */
        markArray = new int[rowNum*columnNum];
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(5);
        paint.setColor(0xff333333);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //子view数量
        cancelViews.clear();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = getChildAt(i);
            Object tag = childAt.getTag();
            if (tag == null){
                throw new SecurityException("This view Tag is Null");
            }
            int index = (int) childAt.getTag();
            cancelViews.put(index,childAt);
            //控件所属行
            int row = index/columnNum;
            //控件所在列
            int col = (index+1)%columnNum==0?columnNum-1:((index+1)%columnNum)-1;
            int left = col*childWidth+col*mySpecValue;
            int right = left+childWidth;
            int top = row*childHeight + row*mySpecValue;
            int bottom = top + childHeight;
            childAt.layout(left,top,right,bottom);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int  index = TouchIndex(ev.getX(),ev.getY());
        LogUtil.d(index+"");
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
    int choseIndex = 0;
    int lastX = 0;
    int lastY = 0;
    int spaceX = 0;
    int spaceY = 0;
    int tempIndex = 0;
    View touchView = null;
    boolean isCanMove = false;
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int tempX = 0;
        int tempY = 0;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.e("TAG","DOWN");
               tempIndex = choseIndex = TouchIndex(event.getX(),event.getY());
                Log.e("TAG","DOWN"+choseIndex);
               if (choseIndex <= 0)return true;
                lastX = (int) event.getX();
                lastY = (int) event.getY();
                touchView = cancelViews.get(choseIndex-1);

                for (Map.Entry<Integer, View> entry : cancelViews.entrySet()) {
                    Log.e("TAG","DOWN"+cancelViews.size()+"_____"+entry.getKey());
                }
                if (touchView== null) return true;
                spaceX = (int) (lastX -touchView.getX());
                spaceY = (int) (lastY - touchView.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                Log.e("TAG","MOVE");
                if (touchView == null)return true;
                  tempX = (int) event.getX();
                  tempY = (int) event.getY();
                  int index = TouchIndex(touchView.getX()+spaceX/2,touchView.getY()+spaceY/2);
                  if (index >0)tempIndex = index;
                Log.e("TAG","MOVE"+tempIndex);
                 touchView.layout(tempX-spaceX,tempY-spaceY,tempX-spaceX+touchView.getWidth(),tempY-spaceY+touchView.getHeight());
                break;
            case MotionEvent.ACTION_UP:
                Log.e("TAG","UP");
                if (touchView == null)return true;
                if (cancelViews.containsKey(tempIndex-1)){
                    View view = cancelViews.get(tempIndex - 1);
                    view.setTag(choseIndex-1);
                }
                touchView.setTag(tempIndex-1);
                requestLayout();
                tempIndex = 0;
                touchView = null;

                //rect = TouchRect(touchView.getX()+spaceX,touchView.getY()+spaceY);
                //touchView.layout(rect.left, rect.top, rect.right, rect.bottom);
                break;
            case MotionEvent.ACTION_CANCEL:
                Log.e("TAG","ACTION_CANCEL");
                if (touchView == null)return true;
                touchView.setTag(tempIndex-1);
                requestLayout();
                tempIndex = 0;
                touchView = null;
                //Rect rect = TouchRect(touchView.getX()+spaceX/2,touchView.getY()+spaceY/2);
                //touchView.layout(rect.left, rect.top, rect.right, rect.bottom);
                return true;
        }
          LogUtil.d(choseIndex+"");
                return true;
    }

    /**
     * 判断点击index
     * @param x x坐标
     * @param y y坐标
     * @return
     */
    private int TouchIndex(float x, float y){
       int row = 0;
       int col = 0;
        for (int i = 0; i < columnNum; i++) {
            if (x> i*childWidth+i*spacingValue&&x<(i*childWidth+i*spacingValue)+childWidth){
                col = i+1;
                break;
            }
        }
        for (int i = 0; i < rowNum; i++) {
            if (y> i*childHeight+i*spacingValue&&y<(i*childHeight+i*spacingValue)+childHeight){
                row = i+1;
                break;
            }
        }
         if (row == 0||col == 0)row=col=0;
        Log.e("TAG","TouchIndex"+row+"____"+col);
        return ((row-1)*columnNum)+col;

    }
    private Rect TouchRect(float x, float y){
         int left = 0;
         int top = 0;
         int right = 0;
         int bottom = 0;
        for (int i = 0; i < columnNum; i++) {
            if (x> i*childWidth+i*spacingValue&&x<(i*childWidth+i*spacingValue)+childWidth){
                left = i*childWidth+i*spacingValue;
                right = left+childWidth;
                break;
            }
        }
        for (int i = 0; i < rowNum; i++) {
            if (y> i*childHeight+i*spacingValue&&y<(i*childHeight+i*spacingValue)+childHeight){
                top = i*childHeight+i*spacingValue;
                bottom = top +childHeight;
                break;
            }
        }

        return new Rect(left,top,right,bottom);

    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        DrawBackground(canvas);
        super.dispatchDraw(canvas);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).draw(canvas);
        }
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        rectF = new RectF();
    }
    private void DrawBackground(Canvas canvas){
        for (int i = 0; i < columnNum*columnNum; i++) {
            //控件所属行
            int row = i/columnNum;
            //控件所在列
            int col = (i+1)%columnNum==0?columnNum-1:((i+1)%columnNum)-1;
            int left = col*childWidth+col*mySpecValue;
            int top =  row*childHeight + row*mySpecValue;
            rectF.set(left,top,left+childWidth,top+childHeight);
            canvas.drawRoundRect(rectF, 50, 50, paint);
        }
    }

    private int dp2px(Context context, int dpValue) {
        if (context == null) {
            return 0;
        }
        DisplayMetrics displayMetrics = getDisplayMetrics(context);
        float density = displayMetrics != null ? displayMetrics.density : 0;
        return (int) (dpValue * density + 0.5f);
    }
}
